<?php
declare (strict_types = 1);

namespace app\service\logic\common\site;

use app\exception\LogicException;
use app\facade\SmsFacade;
use Carbon\Carbon;
use think\facade\Cache;
use think\helper\Str;

final class SiteService
{
    /**
     * 发送验证码
     *
     * @param $params
     * @return mixed
     * @throws LogicException
     */
    public function send($params)
    {
        $mobile = $params['mobile'];

        // 缓一个
        $cacheKey = 'sms_' . $mobile;
        $cacheCountKey = 'sms_' . $mobile . '_count';
        if (Cache::get($cacheKey)) {
            $code = Cache::get($cacheKey);
        } else {
            // 生成验证码
            $code = Str::random(6, 1);
            Cache::set($cacheKey, $code, 600);
        }

        $content = sprintf(lang('app.sms content'), $code);
        $result = SmsFacade::send($mobile, $content);
        if ($result) {
            $expire = Carbon::now()->diffInSeconds(Carbon::today()->endOfDay());
            if (empty(Cache::get($cacheCountKey))) {
                Cache::set($cacheCountKey, 1, $expire);
            } else {
                $count = Cache::get($cacheCountKey);
                if ($count >= 9) {
                    throw new LogicException(lang('app.sms limit'));
                }
                $count++;
                Cache::set($cacheCountKey, $count, $expire);
            }
        }

        return $result;
    }
}
